﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using ExaminationSys.DataAccess;
using ExaminationSys.DataAccess.Entity;
using ExaminationSys.DataAccess.Repository;
using ExaminationSys.Helper;
using Ext.Net;

namespace ExaminationSys.View.Section
{
    public partial class SubSectionInfoList : System.Web.UI.Page
    {
        /// <summary>
        /// 栏目类型
        /// </summary>
        public string SectionID
        {
            get { return Request.QueryString["SectionID"] == null ? string.Empty : Request.QueryString["SectionID"].ToString(); }
        }

        private static readonly SubSectionInfoService Proxy = ObjectFactory<SubSectionInfoService>.Create();
        private static readonly SubSectionDetailInfoService ProxyDetailInfo = ObjectFactory<SubSectionDetailInfoService>.Create();
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!X.IsAjaxRequest)
            {
                var empty = Guid.Empty.ToString();
                X.Js.Call("afterItemClick", empty, empty);
            }

        }

        protected void GetNodes(object sender, NodeLoadEventArgs e)
        {
            if (e.NodeID.Equals("root", StringComparison.OrdinalIgnoreCase))
            {
                var nodes = BuildTreeNodes();
                e.Nodes = nodes;
                
                if(nodes.Count==0)
                {
                    BtnAddDetailNode.Disabled = true;
                   // BtnUp.Disabled = true;
                   // BtnDn.Disabled = true;
                    BtnDelete.Disabled = true;
                }
            }
        }
        [DirectMethod]
        public string Submit()
        {
            NodeCollection nodes = BuildTreeNodes();
            return nodes.ToJson();
        }

        public List<SubSectionInfo> SubSectionInfoCollection { get; set; }

       
        private NodeCollection BuildTreeNodes()
        {
            NodeCollection result = new NodeCollection();
            var items = Proxy.GetPublishList(SectionID);
            if (items == null) return result;
            SubSectionInfoCollection = items;

            var firstNodes = items.Where(c => c.ParentID == c.ID).ToList();
            firstNodes.Sort((x,y) => x.OrderIndex.CompareTo(y.OrderIndex));
            foreach (var firstNode in firstNodes)
            {
                var text = string.Format("{0}({1})", firstNode.Name,
                                         Enum.GetName(typeof (EnumLevel), firstNode.KnowledgeLevel));
                Node node = new Node();
                node.Text = text;// firstNode.Name;
                node.NodeID = firstNode.ID.ToString();
                node.IconCls = "icon-lightning";
                if (firstNode.NodeType == (int)EnumNodeType.知识点)
                    node.Leaf = true;
              
                BindNodes(firstNode, node);
                result.Add(node);
            }

            return result;
        }

        private void BindNodes(SubSectionInfo sectionInfo, Node node)
        {
            var items = SubSectionInfoCollection.Where(c => c.ParentID == sectionInfo.ID && c.ID != sectionInfo.ID).ToList();
            items.Sort((x, y) => x.OrderIndex.CompareTo(y.OrderIndex));
            foreach (var item in items)
            {
                var text = string.Format("{0}({1})", item.Name,
                                          Enum.GetName(typeof(EnumLevel), item.KnowledgeLevel));
                Node childNode = new Node();
                childNode.Text = text;// item.Name;
                childNode.NodeID = item.ID.ToString();
                if (item.NodeType == (int)EnumNodeType.知识点)
                    childNode.Leaf = true;
                
                node.Children.Add(childNode);
                BindNodes(item, childNode);
            }
        }

        public Guid PrevClickItem { get; set; }
        public void NodeClick(object sender, DirectEventArgs e)
        {
         
            var id = e.ExtraParams["Id"];
            var realId = Guid.Empty;
            if (!string.IsNullOrEmpty(id) && Guid.TryParse(id, out realId))
            {
                var items =ProxyDetailInfo.GetListBySubSectionId(realId);
                this.StoreSubSectionInfo.DataSource = items;
                this.StoreSubSectionInfo.DataBind();

                if (PrevClickItem == realId) return;
                realId = Proxy.GetTopParentId(realId);
                PrevClickItem = realId;
                X.Js.Call("afterItemClick", realId, id);

            }
        }

        public Store GridStore { get; set; }
        public string ID { get; set; }

      
        public void BtnAddNode_Click(object sender, DirectEventArgs e)
        {
            var obj = SelectNodeParent.Value;
            if (string.IsNullOrEmpty(obj) || obj == Guid.Empty.ToString())
                TB_ParentNode.Text = "root";
            else
            {
                var id = new Guid(obj);
                var item = Proxy.Get(id);
                if (item != null)
                {
                    if(item.ParentID==item.ID)
                    {
                        TB_NodeText.Text = "";
                        TB_ParentNode.Text = "root";

                    }else
                    {
                        TB_ParentNode.Text = item.Name;
                        
                    }
                   
                }
            }
            HiddenParentID.Value = "c";
            TB_ParentNode.Disabled = true;
            EditNodeWindow.Title = "新增节点";
            EditNodeWindow.Show();
        }

        public void BtnAddDetailNode_Click(object sender, DirectEventArgs e)
        {
            var obj = SelectNode.Value;
            if (string.IsNullOrEmpty(obj) || obj.Equals(Guid.Empty.ToString()))
            {
                MessageBoxHelper.ShowInfo("请先选择一个父节点再添加");
                return;
            }
            var id = new Guid(obj);
            var item = Proxy.Get(id);
            if (item != null)
            {
                if (item.NodeType == (int)EnumNodeType.知识点)
                {
                    MessageBoxHelper.ShowInfo("当前选择的节点类型为知识点,不再在该节点下添加子节点");
                    return;
                }
                TB_ParentNode.Text = item.Name;
            }
            TB_NodeText.Text = "";
            HiddenParentID.Value = "d";
            TB_ParentNode.Disabled = true;
            EditNodeWindow.Title = "新增子节点";
            EditNodeWindow.Show();
            //如果是父节点，则可以添加子，否则不可以
        }

        public void Btn_GoBack(object sender, DirectEventArgs e)
        {
            Response.Redirect("SectionDetailList.aspx");
        }
        public void SaveNode_Click(object sender, DirectEventArgs e)
        {
            var opeator = FormsAuthenticationHelper.GetCurrentUserID();
            if (string.IsNullOrEmpty(opeator))
            {
                Response.Redirect("~/Account/Login.aspx");
                return;
            }
            var nodeText = TB_NodeText.Text.Trim();
            if(string.IsNullOrEmpty(nodeText))
            {
                MessageBoxHelper.ShowError("节点名称不能为空");
                return;
            }
            if(string.IsNullOrWhiteSpace(SectionID))
            {
                MessageBoxHelper.ShowError("栏目ID获取失败");
                return;
            }
            var selectItem = SelectBox_Level.SelectedItem;
            var level = selectItem == null ? -1 : Convert.ToInt32(selectItem.Value);
            if(level==-1)
            {
                MessageBoxHelper.ShowError("请选择难度");
                return;
                
            }
            var nodeTypeItem = SelectBox_NodeType.SelectedItem;
            var nodeType = nodeTypeItem == null ? -1 : Convert.ToInt32(nodeTypeItem.Value);
            if(nodeType==-1)
            {
                MessageBoxHelper.ShowError("请选择节点类型");
                return;
            }

            var ischild = HiddenParentID.Value.Equals("d");
            var parentId = Guid.Empty;
            var curSelectId = Guid.Empty;

          

            var obj = SelectNodeParent.Value;
            curSelectId = new Guid(obj);
            parentId = curSelectId;

          
           
            if (ischild)
            {
                obj = SelectNode.Value;
                if (string.IsNullOrEmpty(obj) || obj.Equals(Guid.Empty.ToString()))
                {
                    MessageBoxHelper.ShowInfo("请先选择一个父节点");
                    return;
                }
                parentId = new Guid(obj);
            }
            else
            {
                
                var tmp = Proxy.Get(parentId);
                if (tmp!=null&&tmp.ID == tmp.ParentID)
                {
                    parentId = Guid.Empty;
                    curSelectId = Guid.Empty;
                }
            }

            
            //selectItem = SelectBoxSubSectionType.SelectedItem;
            //var sectionType = selectItem == null ? -1 : Convert.ToInt32(selectItem.Value);
            var id = Guid.NewGuid();
            var item=new SubSectionInfo();
            item.ID = id;
            item.SectionID = new Guid(SectionID);
            item.Name = nodeText;
            item.ParentID = ischild ? parentId : (parentId == Guid.Empty ? id : parentId);


            var latestIndex = Proxy.LastestIndex(item.ParentID) + 1;
            item.KnowledgeLevel = level;
            //item.SubSectionType = sectionType;
            item.NodeType = nodeType;
            item.Lock = false;
            item.OrderIndex = latestIndex;
            item.Status = 1;
            item.Opeator = opeator;
            item.OpeatorTime = DateTime.Now;

            //id自动生成了，所以父ID不正确 
           var retCode= Proxy.Insert(item);
            if(retCode != 0)
            {
                MessageBoxHelper.ShowInfo("保存成功");
                EditNodeWindow.Hide();

                Node node = new Node();
                node.NodeID = id.ToString();
                node.Text = nodeText;
                node.Leaf = nodeType == 1;
                if(ischild)
                {
                    var sNode = TreePanelSubSection.GetNodeById(parentId);
                    sNode.InsertChild(0, node);
                   
                }
                else
                {
                    if(curSelectId!=Guid.Empty)
                    {
                        var sNode = TreePanelSubSection.GetNodeById(curSelectId);
                        sNode.InsertBefore(node, sNode);
                        
                    }
                    else
                    { 
                        var rootNode = TreePanelSubSection.GetRootNode();
                        rootNode.InsertChild(0, node);
                    }
                }
            }
        }

        [DirectMethod]
        public void MoveNode(string id, string oldParentId, string newParentId)
        {
            if (oldParentId.Equals("root", StringComparison.OrdinalIgnoreCase) &&
                newParentId.Equals("root", StringComparison.OrdinalIgnoreCase))
            {
                return;
            }
            if (!string.IsNullOrWhiteSpace(id))
            {

                var item = Proxy.Get(new Guid(id));
                if (item != null)
                {
                    item.OpeatorTime = DateTime.Now;
                    if (newParentId.Equals("root", StringComparison.OrdinalIgnoreCase))
                    {
                        item.OrderIndex = 1;
                        item.ParentID = item.ID;
                        Proxy.Update(item);
                    }
                    else
                    {
                        Guid pid = Guid.Empty;
                        if (Guid.TryParse(newParentId, out pid))
                        {

                            item.ParentID = pid;
                            Proxy.Update(item);
                        }
                    }
                }
            }

        }

        [DirectMethod]
        public void NodeDoConfirm()
        {
            var node = SelectNode.Value;
            if (string.IsNullOrWhiteSpace(node)||node==Guid.Empty.ToString())
            {
                MessageBoxHelper.ShowWarning("请选择要删除的节点");
                return;
            }
            var hasChild = Proxy.HasSubNodes(new Guid(node));
            if(hasChild)
            {
                X.Msg.Confirm("提示", "该节点下存在子节点，是否继续删除?", new MessageBoxButtonsConfig
                {
                    Yes = new MessageBoxButtonConfig
                    {
                        Handler = "X.DoDeleteNode()",
                        Text = "是"
                    },
                    No = new MessageBoxButtonConfig
                    {
                        Text = "否"
                    }
                }).Show();
                
            }
            else
            {
                X.Msg.Confirm("提示", "是否删除选中记录?", new MessageBoxButtonsConfig
                {
                    Yes = new MessageBoxButtonConfig
                    {
                        Handler = "X.DoDeleteNode()",
                        Text = "是"
                    },
                    No = new MessageBoxButtonConfig
                    {
                        Text = "否"
                    }
                }).Show();
                
            }
        }
        [DirectMethod]
        public void DoDeleteNode()
        {
           
            var node = SelectNode.Value;
            var success = Proxy.Delete(node);
            if (success)
            {
                var sNode=TreePanelSubSection.GetNodeById(node);
                sNode.Remove();
                MessageBoxHelper.ShowInfo("保存成功");

            }
        }


        #region gridpanel 操作

        [DirectMethod]
        public void DoConfirm()
        {
            RowSelectionModel sm = GridPanelSubSectionInfo.SelectionModel.Primary as RowSelectionModel;

            if (sm.SelectedRows.Count == 0)
            {
                MessageBoxHelper.ShowWarning("请选择要删除的记录");
                return;
            }
            X.Msg.Confirm("提示", "是否删除选中记录?", new MessageBoxButtonsConfig
            {
                Yes = new MessageBoxButtonConfig
                {
                    Handler = "X.DoDelete()",
                    Text = "是"
                },
                No = new MessageBoxButtonConfig
                {
                    Text = "否"
                }
            }).Show();
        }
        protected void StoreSubSectionInfo_RefreshData(object sender, StoreReadDataEventArgs e)
        {
            var obj = SelectNode.Value;
            if (!string.IsNullOrWhiteSpace(obj))
            {

                var items = ProxyDetailInfo.GetListBySubSectionId(new Guid(obj));
                this.StoreSubSectionInfo.DataSource = items;
                this.StoreSubSectionInfo.DataBind();
            }
        }
        protected void Page_Init(object sender, EventArgs e)
        {
            this.SubSectionInfoListEditWindow.GridStore = this.StoreSubSectionInfo;
        }
        protected void ShowDetails(string id)
        {

            SubSectionInfoListEditWindow.GridStore = StoreSubSectionInfo;
            this.SubSectionInfoListEditWindow.SetData(id, SelectNode.Value);
            this.SubSectionInfoListEditWindow.Show();

        }

        protected void BtnAddDetail_Click(object sender, DirectEventArgs e)
        {
            if (string.IsNullOrWhiteSpace(SelectNode.Value)||SelectNode.Value==Guid.Empty.ToString())
            {
                MessageBoxHelper.ShowInfo("请先选择一个知识点");
                return;
            }
            SubSectionInfoListEditWindow.GridStore = StoreSubSectionInfo;
            this.SubSectionInfoListEditWindow.SetData("", SelectNode.Value);
            this.SubSectionInfoListEditWindow.Show();
        }

        protected void Command(object sender, DirectEventArgs e)
        {
            var command = e.ExtraParams["command"];

            var id = e.ExtraParams["Id"];
            if (string.IsNullOrWhiteSpace(id))
            {
                MessageBoxHelper.ShowInfo("获取ID失败");
                return;
            }

            if (string.IsNullOrWhiteSpace(SelectNode.Value) || SelectNode.Value == Guid.Empty.ToString())
            {
                MessageBoxHelper.ShowInfo("请先选择一个知识点");
                return;
            }

            if (command.Equals("edit", StringComparison.OrdinalIgnoreCase))
            {
                ShowDetails(id);
            }
            else
            {
                var objid = new Guid(id);
                if(Proxy.HasSubNodes(objid))
                {
                    MessageBoxHelper.ShowWarning("该节点下存在子节点，不能删除");
                    return;
                }
                var entity = ProxyDetailInfo.Get(objid);
                if (entity != null)
                {
                    entity.Status = 0;
                    var success = ProxyDetailInfo.Update(entity);
                    if (success)
                    {
                        StoreSubSectionInfo.Remove(entity.ID);
                        MessageBoxHelper.ShowInfo("删除成功");
                    }
                }
            }
        }

        protected void BatchLock_Click(object sender, DirectEventArgs e)
        {
            RowSelectionModel sm = GridPanelSubSectionInfo.SelectionModel.Primary as RowSelectionModel;

            if (sm.SelectedRows.Count == 0)
            {
                MessageBoxHelper.ShowWarning("请选择要锁定的记录");
                return;
            }
            List<string> ids = new List<string>();
            foreach (var row in sm.SelectedRows)
            {
                ids.Add(row.RecordID);
            }
            var success = ProxyDetailInfo.Lock(ids, true);
            if (success)
            {
                var id = new Guid(SelectNode.Value);
                var items = ProxyDetailInfo.GetListBySubSectionId(id);
                this.StoreSubSectionInfo.DataSource = items;
                this.StoreSubSectionInfo.DataBind();
                MessageBoxHelper.ShowInfo("保存成功");
            }
        }

          [DirectMethod]
        public void DoDelete()
        {
            RowSelectionModel sm = GridPanelSubSectionInfo.SelectionModel.Primary as RowSelectionModel;

            if (sm.SelectedRows.Count == 0)
            {
                MessageBoxHelper.ShowWarning("请选择要删除的记录");
                return;
            }
            List<string> ids = new List<string>();
            foreach (var row in sm.SelectedRows)
            {
                ids.Add(row.RecordID);
            }
            var success = ProxyDetailInfo.Delete(ids);
            if (success)
            {
                ids.ForEach(id =>
                            StoreSubSectionInfo.Remove(id));
                MessageBoxHelper.ShowInfo("保存成功");
            }
        }

        protected void BatchUnLock_Click(object sender, DirectEventArgs e)
        {
            RowSelectionModel sm = GridPanelSubSectionInfo.SelectionModel.Primary as RowSelectionModel;

            if (sm.SelectedRows.Count == 0)
            {
                MessageBoxHelper.ShowWarning("请选择要解锁的记录");
                return;
            }
            List<string> ids = new List<string>();
            foreach (var row in sm.SelectedRows)
            {
                ids.Add(row.RecordID);
            }
            var success = ProxyDetailInfo.Lock(ids, false);
            if (success)
            {
                var id = new Guid(SelectNode.Value);
                var items = ProxyDetailInfo.GetListBySubSectionId(id);
                this.StoreSubSectionInfo.DataSource = items;
                this.StoreSubSectionInfo.DataBind();
                MessageBoxHelper.ShowInfo("保存成功");
            }
        }

        protected void MoveUp_Click(object sender, DirectEventArgs e)
        {
            RowSelectionModel sm = GridPanelSubSectionInfo.SelectionModel.Primary as RowSelectionModel;

            if (sm.SelectedRows.Count == 0)
            {
                MessageBoxHelper.ShowWarning("请选择要锁定的记录");
                return;
            }
            List<string> ids = new List<string>();
            foreach (var row in sm.SelectedRows)
            {
                ids.Add(row.RecordID);
            }
            //
            //var success = Proxy.Lock(ids, true);
            //if (success)
            //{
            //    var id = new Guid(SelectNode.Value);
            //    var items = Proxy.GetListByParentId(id);
            //    this.StoreSubSectionInfo.DataSource = items;
            //    this.StoreSubSectionInfo.DataBind();
            //    MessageBoxHelper.ShowInfo("保存成功");
            //}
        }

        protected void MoveDn_Click(object sender, DirectEventArgs e)
        {
            RowSelectionModel sm = GridPanelSubSectionInfo.SelectionModel.Primary as RowSelectionModel;

            if (sm.SelectedRows.Count == 0)
            {
                MessageBoxHelper.ShowWarning("请选择要锁定的记录");
                return;
            }
            List<string> ids = new List<string>();
            foreach (var row in sm.SelectedRows)
            {
                ids.Add(row.RecordID);
            }
            //var success = Proxy.Lock(ids, true);
            //if (success)
            //{
            //    var id = new Guid(SelectNode.Value);
            //    var items = Proxy.GetListByParentId(id);
            //    this.StoreSubSectionInfo.DataSource = items;
            //    this.StoreSubSectionInfo.DataBind();
            //    MessageBoxHelper.ShowInfo("保存成功");
            //}
        }

        #endregion
    }
}